# 配置文件读取器

import os

def read_or_create(path:str,default_config:str=None)->dict:
    if not os.path.exists(path): 
        with open(path,'w',encoding='utf-8') as file:
            file.write(default_config)
            file.close()
    return read_ini(path)

# 配置样例请见sample_config.ini
def read_ini(path:str)->dict:
    '''
    读取配置文件，样例为sample_config.ini
    path: 文件路径
    返回值: 一个字典。该字典中含有{配置组名:配置字典}的键值对，例如
    {
        "app1":{
            "key1":"value1",
            "key2":"value2"
        }
    }
    '''
    buf=None
    with open(path,'r',encoding='utf-8') as fp:
        buf=fp.readlines()
        fp.close()
    ret={}
    current_app="default"
    for x in buf:
        pos=x.find('#')
        if(pos>=0): 
            line=x[0:pos].strip()
        else:
            line=x.strip()
        if(line==''):continue
        if(line[0]=='[' and line[-1]==']'): #find an app
            current_app=line[1:-1]
            ret[current_app]={}
        else:
            pos=line.find('=')
            parname=line[0:pos].strip()
            parval=line[pos+1:].strip()
            ret[current_app][parname]=parval
    return ret